﻿using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;

using DataAccess.Solr;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class ProductController : BaseController
    {

        public ActionResult Index()
        {
            SolrProductBLL bll = new SolrProductBLL();

            return View(bll.GetProductClass());
        }
        Random rd = new Random();
        public ActionResult Kouling(int? id, string pid)
        {
            if (id.HasValue && !string.IsNullOrEmpty(pid))
            {
                var model = new SolrProductDetails().GetProductDetailsByProductInfo(pid);
                if (model != null)
                {


                    string[] tb = SysConfig.tb_open.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                    int index = rd.Next(tb.Length);
                    if (index % 2 != 0)
                    {
                        index = index - 1;
                    }

                    string kl = DataAccess.TB.Tkl.CreateToken(model.pictUrl,
                       model.title, model.couponActivityId,
                        SysConfig.def_pid,
                        model.auctionId.ToString(), "3254152761",
                       tb[index],
                       tb[index + 1]);
                    string shortUrl = "";
                    try
                    {
                        string stractivityUrl = string.Format("http://uland.taobao.com/coupon/edetail?activityId={0}&pid={1}&itemId={2}", model.couponActivityId, SysConfig.def_pid, model.auctionId);
                        shortUrl = DataAccess.SortUrl.CreateShortUrl(stractivityUrl);
                    }
                    catch (Exception)
                    {

                        shortUrl = "";
                    }
                    string Html = "";
                    if (id == 1) //微信推广
                    {
                    Html = string.Format(@"{0}
【推荐理由】{1}
┄┄┄┄┄┄
原　价：【 {2}】元
券后价：【 {3}】元 
┄┄┄┄┄┄
复制这条消息, 打开【手机淘宝】即可购买{4}つ http://f-2.cc/{6}
（优惠汇总）点此进入要什么就搜索什么：http://{5}

", model.title, model.Introduce, model.zkPrice, model.Price, kl, base.SysConfig.domain + "/shop/admin.html", shortUrl);
                    }
                    else//qq推广
                    {
                        Html = string.Format(@"{0}
【推荐理由】{1}
┄┄┄┄┄┄
原　价：【 {2}】元
券后价：【 {3}】元 
┄┄┄┄┄┄
复制这条消息, 打开【手机淘宝】即可购买{4}つ http://f-2.cc/{6}
（优惠汇总）点此进入要什么就搜索什么：http://{5}

", model.title, model.Introduce, model.zkPrice, model.Price, kl, base.SysConfig.domain + "/shop/admin.html", shortUrl);
                    }
                    return Json(new { State = true, Message = "查询成功", date = Html });
                }
            }
            return null;
        }

        //[HttpPost]
        public JsonResult GetProducts()
        {

            SolrProductBLL bll = new SolrProductBLL();
            int cid = XYD.Common.Request.GetQueryInt("cid", 0);
            string keyword = XYD.Common.Request.GetQueryString("key");
            int offset = XYD.Common.Request.GetQueryInt("offset", 1);
            offset = offset > 1 ? (offset - 1) * 20  : 0;
            
            int oid = XYD.Common.Request.GetQueryInt("oid", 0);

            #region 拼接solr请求条件字符
            //string strwhere = "(couponActivityId:['' TO *])";
            string strwhere = "(biz30day:[0 TO *])";
            if (cid > 0)
            {
                strwhere += string.Format("AND(DataTypeID:{0})", cid);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                strwhere += "AND(";
                strwhere += string.Format("(productname:{0})", keyword);
                strwhere += ")";
            }
            #endregion
            string OrderBy = "id desc";
            switch (oid)
            {
                case 2:
                    OrderBy = "synchro_date desc";
                    break;
                case 3:
                    OrderBy = "biz30day desc";
                    break;
                case 4:
                    OrderBy = "tkRate desc";
                    break;
                case 5:
                    OrderBy = "zkPrice asc";
                    break;
            }
            PagingList<ProductListModel> plist = bll.GetProductListModelPage(strwhere, offset, 20, OrderBy);
            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            return Json(new { State = true, Message = "查询成功", total = plist.Total, rows = plist });

        }

        public JsonResult GetProducts_table()
        {

            SolrProductBLL bll = new SolrProductBLL();
            int cid = XYD.Common.Request.GetQueryInt("cid", 0);
            string keyword = XYD.Common.Request.GetFormString("key");
            int offset = XYD.Common.Request.GetFormInt("offset", 1);
            int limit = XYD.Common.Request.GetFormInt("limit", 10);
            ;

            int oid = XYD.Common.Request.GetQueryInt("oid", 0);





            #region 拼接solr请求条件字符
            //string strwhere = "(couponActivityId:['' TO *])";
            string strwhere = "(biz30day:[0 TO *])";
            if (cid > 0)
            {
                strwhere += string.Format("AND(DataTypeID:{0})", cid);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                strwhere += "AND(";
                strwhere += string.Format("(productname:{0})", keyword);
                strwhere += ")";
            }
            #endregion
            string OrderBy = "id desc";
            switch (oid)
            {
                case 2:
                    OrderBy = "synchro_date desc";
                    break;
                case 3:
                    OrderBy = "biz30day desc";
                    break;
                case 4:
                    OrderBy = "tkRate desc";
                    break;
                case 5:
                    OrderBy = "zkPrice asc";
                    break;
            }
            PagingList<ProductListModel> plist = bll.GetProductListModelPage(strwhere, offset, limit, OrderBy);
            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";

            result.Datas = new PageData<ProductListModel> { Total = plist.Total, Rows = plist.CurrentPageList, PageIndex = (offset / limit) + 1, PageSize = limit };


            return Json(result);

        }

        /// <summary>
        /// 查询商品详情
        /// </summary>
        /// <returns></returns>
        public JsonResult Goods()
        {
            Result result = new Result();
            SolrProductDetails bll = new SolrProductDetails();
            string id = XYD.Common.Request.GetQueryString("id");
            if (!string.IsNullOrEmpty(id) && id != "0")
            {
                var model = bll.GetProductDetailsByProductInfo(id);
                if (model != null)
                {

                    result.State = true;
                    result.Message = "查询成功";
                    return Json(new { State = true, Message = "查询成功", rows = model });
                }
            }
            result.State = false;
            result.Message = "查询失败";
            return Json(new { State = true, Message = "查询成功" });

        }

        public ActionResult ProductList()
        {
            SolrProductBLL bll = new SolrProductBLL();

            return View(bll.GetProductClass());
        }

        public ActionResult MyGoods()
        {
            SysConfigDAL scDal = new SysConfigDAL();
            var model = scDal.Get_PromoterId(UserSession.user_id);

            if (model == null)
            {
                return Content("<script>alert('请先在 系统管理中完成站点配置！'); location.href='/'</script>");
            }

            ViewBag.Type = string.IsNullOrEmpty(model.collecting_source_type) ? "" : model.collecting_source_type;

            SolrProductBLL bll = new SolrProductBLL();

            return View(bll.GetProductClass());
           
        }

        [HttpPost]
        public JsonResult collecting_source_type(string type)
        {
            Result res = new Result() { State = false, Message = "请求出错" };
            //string type = XYD.Common.Request.GetFormString("type");
            if (string.IsNullOrEmpty(type))
            {
                res.Message = "参数不正确";
            }
            else
            {
                SysConfigDAL scDal = new SysConfigDAL();
                if (scDal.UpdateCollectingSourceType(UserSession.user_id.ToString(), type.TrimEnd(',')))
                {
                    res.State = true;
                    res.Message = "设置成功";
                }
                else
                    res.Message = "更新失败";
            }


            return Json(res);
        }


        [HttpPost]
        public JsonResult AddMyShop(string pids)
        {
            MyProductDAL dal = new MyProductDAL();

            Result res = new Result() { State = false, Message = "操作失败" };
            if (string.IsNullOrEmpty(pids))
                res.Message = "请选择商品";
            else
            {
                List<MyProduct> list = new List<MyProduct>();
                var newPids = pids.Split(',');
                foreach (var pid in newPids)
                {
                    if (!string.IsNullOrEmpty(pid))
                    {
                        list.Add(new MyProduct()
                        {
                            createtime = DateTime.Now,
                            is_del = false,
                            is_send = false,
                            product_id = pid,
                            promoter_id = UserSession.user_id
                        });
                    }



                }

                if (list != null && list.Count > 0)
                {
                    if (dal.Insert(list))
                    {
                        res.State = true;
                        res.Message = "成功";

                    }
                }
                else
                    res.Message = "请选择商品";



            }


            return Json(res);

        }



        public JsonResult GetMyProduct()
        {
            int cid = XYD.Common.Request.GetQueryInt("cid", 0);
            string keyword = XYD.Common.Request.GetFormString("key");
            int offset = XYD.Common.Request.GetFormInt("offset", 0);
            int limit = XYD.Common.Request.GetFormInt("limit", 10);
            ;

            int oid = XYD.Common.Request.GetQueryInt("oid", 0);




            MyProductDAL dal = new MyProductDAL();
            string where = " is_del=0 and promoter_id=" + UserSession.user_id;
            int count = 0;
            var list = dal.ListPage(where, "", limit, (offset / limit) + 1, null, out count);
            
            var newList=new List<MyProductDTO>();
          

            
           
            List<ProductIndex> lists = new List<ProductIndex>();
            if (list != null && list.Count > 0)
            {
                string str = "";
                foreach (var item in list)
                {
                    str = str + " id:" + item.product_id + " OR";
                }
                if (str != "")
                    str = "(" + str.Substring(0, str.Length - 2) + ")";


                lists = new SolrIndexInfoBLL().GetProductDetailList(str);

            }
            MyProduct a = new MyProductDTO();

          

            list.ForEach(l => {
                MyProductDTO item = new MyProductDTO();

                item.id = l.id;
                item.product_id = l.product_id;
                item.createtime = l.createtime;
                item.is_send = l.is_send;
                item.is_del = l.is_del;

                item.promoter_id = l.promoter_id;

                var sole_p = lists.Find(ls => ls.auctionId.ToString() == l.product_id);
                if (sole_p != null)
                {
                    item.auctionUrl = "";//sole_p.auctionUrl;
                    item.pictUrl = sole_p.pictUrl;
                    item.title = sole_p.title;
                    item.zkPrice = sole_p.zkPrice;

                    item.userType = sole_p.userType;
                    item.DataTypeID = 0;//sole_p.DataTypeID;
                    item.couponAmount = sole_p.couponAmount;
                    newList.Add(item);
                }
            });
             Result result = new Result();
            result.State = true;
            result.Message = "查询成功";

            result.Datas = new PageData<MyProductDTO> { Total = count, Rows = newList, PageIndex = (offset / limit) + 1, PageSize = limit };
             return Json(result);



        }

        [HttpPost]
        public JsonResult DeleteMyProduct(string pids)
        {
            Result res = new Result() { State = false, Message = "操作失败" };
            if (string.IsNullOrEmpty(pids))
                res.Message = "请选择商品";
            else
            {
                MyProductDAL dal = new MyProductDAL();

                var ids = "";

                var pids_s = pids.Split(',');
                foreach (var item in pids_s)
                {
                    if(!string.IsNullOrEmpty(item))
                    ids += int.Parse(item).ToString()+",";
                }

                if (dal.Delete_ids(ids.TrimEnd(','), UserSession.user_id.ToString()))
                {
                    res.State = true;
                    res.Message = "操作成功";

                    
                
                } 
            }


            return Json(res);
        }


    }
}